<template>
  <div class="stock-in">
    <el-row :gutter="20">
      <!-- 左侧商品列表 -->
      <el-col :span="14">
        <el-card>
          <div slot="header" class="clearfix">
            <span>商品列表</span>
          </div>
          
          <!-- 商品搜索 -->
          <el-form :inline="true" :model="productSearchForm" class="search-form">
            <el-form-item>
              <el-input 
                v-model="productSearchForm.keyword" 
                placeholder="搜索商品名称/编号"
                prefix-icon="el-icon-search"
                clearable
                @keyup.enter.native="searchProducts">
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-select 
                v-model="productSearchForm.categoryId" 
                placeholder="商品分类" 
                clearable
                @change="searchProducts">
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchProducts">搜索</el-button>
              <el-button @click="resetProductSearch">重置</el-button>
            </el-form-item>
          </el-form>
          
          <!-- 商品列表表格 -->
          <el-table 
            :data="productList" 
            style="width: 100%" 
            border
            v-loading="productLoading"
            height="450">
            <el-table-column prop="code" label="商品编号" width="120"></el-table-column>
            <el-table-column prop="name" label="商品名称" width="130"></el-table-column>
            <el-table-column prop="category" label="分类" width="80"></el-table-column>
            <el-table-column 
              prop="stock"
              label="库存" 
              width="70" 
              align="center">
              <template slot-scope="scope">
                <span style="font-weight: bold; color: #ff6b00;">
                  {{ typeof scope.row.stock === 'number' ? scope.row.stock : 0 }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格" width="80">
              <template slot-scope="scope">
                ¥{{ scope.row.price.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="60">
              <template slot-scope="scope">
                <el-button 
                  type="primary" 
                  size="mini" 
                  icon="el-icon-plus" 
                  circle
                  @click="addProductToForm(scope.row)">
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 商品列表分页 -->
          <div class="pagination-container">
            <el-pagination
              @size-change="handleProductSizeChange"
              @current-change="handleProductCurrentChange"
              :current-page="productPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="productPageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="productTotal">
            </el-pagination>
          </div>

          <!-- 添加一条文字强调库存列 -->
          <div style="margin: 10px 0; color: #ff6b00; font-weight: bold; font-size: 12px;">
            * 商品列表中的库存数据来自后端Integer stock字段
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧入库表单 -->
      <el-col :span="10">
        <el-card>
          <div slot="header" class="clearfix">
            <span>新增入库</span>
          </div>
          
          <el-form :model="stockInForm" :rules="rules" ref="stockInForm" label-width="100px">
            <el-form-item label="供应商" prop="supplier">
              <el-select v-model="stockInForm.supplier" placeholder="请选择供应商" style="width: 100%">
                <el-option label="供应商A" value="supplierA"></el-option>
                <el-option label="供应商B" value="supplierB"></el-option>
                <el-option label="供应商C" value="supplierC"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="入库商品">
              <el-table :data="stockInForm.items" border max-height="250">
                <el-table-column label="商品名称" width="180">
                  <template slot-scope="scope">
                    {{ scope.row.name }}
                  </template>
                </el-table-column>
                <el-table-column label="当前库存" width="80">
                  <template slot-scope="scope">
                    {{ scope.row.stock }}
                  </template>
                </el-table-column>
                <el-table-column label="数量" width="100">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.quantity" :min="1" size="mini"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="单价" width="100">
                  <template slot-scope="scope">
                    <el-input-number 
                      v-model="scope.row.price" 
                      :precision="2" 
                      :step="0.1" 
                      :min="0"
                      size="mini">
                    </el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="小计" width="100">
                  <template slot-scope="scope">
                    ¥{{ (scope.row.quantity * scope.row.price).toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="60">
                  <template slot-scope="scope">
                    <el-button 
                      type="danger" 
                      icon="el-icon-delete" 
                      circle 
                      size="mini"
                      @click="handleRemoveItem(scope.$index)">
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="stockInForm.remark" rows="3"></el-input>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="handleSubmit">提交入库</el-button>
              <el-button @click="resetStockInForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 入库记录列表的代码保持不变... -->
    <el-card style="margin-top: 20px;">
      <div slot="header" class="clearfix">
        <span>入库记录</span>
      </div>
      
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="入库单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入入库单号"></el-input>
        </el-form-item>
        <el-form-item label="入库时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="入库状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="待入库" value="pending"></el-option>
            <el-option label="已入库" value="completed"></el-option>
            <el-option label="已取消" value="cancelled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 入库记录表格 -->
      <el-table :data="stockInList" style="width: 100%" border>
        <el-table-column prop="orderNo" label="入库单号" width="180"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column prop="supplier" label="供应商" width="150"></el-table-column>
        <el-table-column prop="totalAmount" label="总金额" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="操作人" width="120"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleDetail(scope.row)">详情</el-button>
            <el-button 
              v-if="scope.row.status === 'pending'"
              size="mini" 
              type="text" 
              @click="handleComplete(scope.row)">完成入库</el-button>
            <el-button 
              v-if="scope.row.status === 'pending'"
              size="mini" 
              type="text" 
              @click="handleCancel(scope.row)">取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 入库详情对话框 -->
    <el-dialog title="入库详情" :visible.sync="detailVisible" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="入库单号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentOrder.createTime }}</el-descriptions-item>
        <el-descriptions-item label="供应商">{{ currentOrder.supplier }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentOrder.status)">
            {{ getStatusText(currentOrder.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作人">{{ currentOrder.operator }}</el-descriptions-item>
        <el-descriptions-item label="总金额">¥{{ currentOrder.totalAmount?.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentOrder.remark }}</el-descriptions-item>
      </el-descriptions>

      <el-table :data="currentOrder.items" style="width: 100%; margin-top: 20px;" border>
        <el-table-column prop="productName" label="商品名称"></el-table-column>
        <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
        <el-table-column prop="price" label="单价" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="subtotal" label="小计" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.subtotal.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="当前库存" width="100"></el-table-column>
      </el-table>
    </el-dialog>

    <!-- 添加直接测试输出：显示第一行的stock值（如果存在） -->
    <div v-if="productList && productList.length > 0" style="display: none;">
      调试信息 - 首行库存: {{ productList[0].stock }} 
      类型: {{ typeof productList[0].stock }}
    </div>
  </div>
</template>

<script>
export default {
  name: 'StockInView',
  data() {
    return {
      searchForm: {
        orderNo: '',
        dateRange: [],
        status: ''
      },
      stockInList: [
        {
          orderNo: 'RK202403030001',
          createTime: '2024-03-03 10:00:00',
          supplier: '供应商A',
          totalAmount: 1500.00,
          status: 'pending',
          operator: '张三',
          remark: '常规补货',
          items: [
            {
              productName: '可口可乐',
              quantity: 100,
              price: 2.50,
              subtotal: 250.00
            },
            {
              productName: '康师傅方便面',
              quantity: 50,
              price: 3.00,
              subtotal: 150.00
            }
          ]
        }
      ],
      currentPage: 1,
      pageSize: 10,
      total: 100,
      dialogVisible: false,
      dialogType: 'add',
      dialogTitle: '新增入库',
      stockInForm: {
        supplier: '',
        items: [],
        remark: ''
      },
      rules: {
        supplier: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ]
      },
      detailVisible: false,
      currentOrder: {},
      
      // 新增商品列表相关数据
      productSearchForm: {
        keyword: '',
        categoryId: ''
      },
      productList: [],
      productLoading: false,
      productPage: 1,
      productPageSize: 10,
      productTotal: 0,
      categoryOptions: [],
    }
  },
  created() {
    // 页面加载时获取商品列表和分类
    this.loadCategories();
    
    // 先添加一些测试数据以验证表格布局
    this.productList = [
      {id: '1', code: '6903244950756', name: '心相印牌面巾纸', category: '日用品', price: 3.50, stock: 59},
      {id: '2', code: '1234567890', name: '可乐', category: '饮料', price: 3.00, stock: 26},
      {id: '3', code: '6943297601410', name: '罗红霉素胶囊', category: '药品', price: 18.00, stock: 20},
      {id: '4', code: '9876543210', name: '雪碧', category: '饮料', price: 3.00, stock: 13}
    ];
    
    // 设置延迟后再从API获取真实数据
    setTimeout(() => {
      this.searchProducts();
    }, 500);
  },
  methods: {
    // 获取商品分类
    loadCategories() {
      this.$http.get('/category/getAllCategory')
        .then(response => {
          if (response.data && Array.isArray(response.data)) {
            this.categoryOptions = response.data.map(item => ({
              id: item.id,
              name: item.name
            }));
          } else {
            this.categoryOptions = [];
          }
        })
        .catch(error => {
          console.error('获取分类失败:', error);
          this.$message.error('获取分类失败');
          this.categoryOptions = [];
        });
    },
    
    // 搜索商品
    searchProducts() {
      this.productLoading = true;
      
      const params = {
        page: this.productPage,
        pageSize: this.productPageSize,
        keyword: this.productSearchForm.keyword || ''
      };
      
      if (this.productSearchForm.categoryId) {
        params.categoryId = this.productSearchForm.categoryId;
      }
      
      this.$http.get('/product/list', { params })
        .then(response => {
          if (response.code === 200 && response.data) {
            // 直接使用records数据，不做过多处理
            this.productList = response.data.records || [];
            this.productTotal = response.data.total || 0;
            
            // 打印每个记录的stock值，用于调试
            console.log('库存数据:', this.productList.map(item => 
              `${item.name}: stock=${item.stock}`).join(', '));
          } else {
            this.productList = [];
            this.productTotal = 0;
            console.error('API返回错误:', response);
          }
        })
        .catch(error => {
          console.error('获取商品列表失败:', error);
          this.$message.error('获取商品列表失败');
          this.productList = [];
          this.productTotal = 0;
        })
        .finally(() => {
          this.productLoading = false;
        });
    },
    
    // 重置商品搜索条件
    resetProductSearch() {
      this.productSearchForm = {
        keyword: '',
        categoryId: ''
      };
      this.productPage = 1;
      this.searchProducts();
    },
    
    // 处理商品分页变化
    handleProductSizeChange(size) {
      this.productPageSize = size;
      this.searchProducts();
    },
    
    handleProductCurrentChange(page) {
      this.productPage = page;
      this.searchProducts();
    },
    
    // 添加商品到入库表单
    addProductToForm(product) {
      // 检查商品是否已在表单中
      const existingIndex = this.stockInForm.items.findIndex(item => item.productId === product.id);
      
      if (existingIndex >= 0) {
        // 商品已存在，增加数量
        this.stockInForm.items[existingIndex].quantity++;
      } else {
        // 添加新商品
        this.stockInForm.items.push({
          productId: product.id,
          name: product.name,
          price: product.price,
          quantity: 1,
          stock: product.stock,
          code: product.code,
          version: product.version
        });
      }
      
      // 提示用户
      this.$message.success(`已添加商品: ${product.name}`);
    },
    
    // 移除入库表单中的商品
    handleRemoveItem(index) {
      this.stockInForm.items.splice(index, 1);
    },
    
    // 重置入库表单
    resetStockInForm() {
      this.stockInForm = {
        supplier: '',
        items: [],
        remark: ''
      };
    },
    
    // 提交入库表单
    handleSubmit() {
      this.$refs.stockInForm.validate(valid => {
        if (valid) {
          if (this.stockInForm.items.length === 0) {
            this.$message.warning('请至少添加一件商品');
            return;
          }
          
          // 构建提交数据
          const submitData = {
            supplier: this.stockInForm.supplier,
            remark: this.stockInForm.remark,
            items: this.stockInForm.items.map(item => ({
              productId: item.productId,
              quantity: item.quantity,
              price: item.price,
              version: item.version
            }))
          };
          
          // TODO: 发送API请求保存入库单
          console.log('提交入库数据:', submitData);
          
          // 模拟保存成功
          this.$message.success('入库单保存成功');
          this.resetStockInForm();
          
          // 刷新商品列表
          this.searchProducts();
        }
      });
    },
    
    // 以下是原有的方法，保持不变
    getStatusType(status) {
      const types = {
        pending: 'warning',
        completed: 'success',
        cancelled: 'info'
      }
      return types[status] || 'info'
    },
    getStatusText(status) {
      const texts = {
        pending: '待入库',
        completed: '已入库',
        cancelled: '已取消'
      }
      return texts[status] || '未知'
    },
    handleSearch() {
      // TODO: 实现搜索逻辑
      console.log('搜索条件：', this.searchForm)
    },
    resetSearch() {
      this.searchForm = {
        orderNo: '',
        dateRange: [],
        status: ''
      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      // TODO: 重新加载数据
    },
    handleCurrentChange(val) {
      this.currentPage = val
      // TODO: 重新加载数据
    },
    handleDetail(row) {
      this.detailVisible = true;
      this.currentOrder = JSON.parse(JSON.stringify(row));
      
      // 获取商品的最新库存信息
      if (this.currentOrder.items && this.currentOrder.items.length > 0) {
        this.currentOrder.items.forEach(item => {
          // 获取商品的最新库存
          this.getProductById(item.productId).then(productInfo => {
            if (productInfo) {
              item.stock = productInfo.stock;
            }
          });
        });
      }
    },
    handleComplete() {
      this.$confirm('确认完成入库吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 实现完成入库逻辑
        this.$message.success('入库完成')
      }).catch(() => {})
    },
    handleCancel() {
      this.$confirm('确认取消入库吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 实现取消入库逻辑
        this.$message.success('已取消入库')
      }).catch(() => {})
    },
    
    // 根据ID获取商品详情
    getProductById(productId) {
      return this.$http.get(`/product/detail/${productId}`)
        .then(response => {
          if (response.data) {
            // 确保返回的商品数据有stock字段
            const product = response.data;
            if (product.stock === undefined && product.number !== undefined) {
              product.stock = product.number;
            }
            if (product.stock !== undefined) {
              product.stock = Number(product.stock);
            } else {
              product.stock = 0;
            }
            return product;
          }
          return null;
        })
        .catch(error => {
          console.error('获取商品详情失败:', error);
          return null;
        });
    }
  }
}
</script>

<style scoped>
.stock-in {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-row {
  margin-bottom: 20px;
}

.el-card {
  margin-bottom: 20px;
}

/* 确保库存列可见 */
.el-table {
  width: 100% !important;
  table-layout: fixed !important;
}

.el-table__body-wrapper {
  overflow-x: auto !important;
}

/* 强制展示库存列 */
:deep(.el-table__fixed-right) {
  display: block !important;
  z-index: 10;
}

/* 库存列高亮样式 */
:deep(.el-table td.is-center) {
  background-color: rgba(255, 107, 0, 0.05);
}
</style> 